package svc

import (
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/go-zero/zrpc"
	"group-card/api/internal/config"
	"group-card/api/internal/middleware"
	"group-card/common/tool"
	"group-card/rpc/card/card"
	"group-card/rpc/sys/sys"
	"log"
	"time"
)

type ServiceContext struct {
	Config    config.Config
	CheckUrl  rest.Middleware
	Redis     *redis.Redis
	OssClient *oss.Client
	Sys       sys.Sys
	Card      card.Card
}

func NewServiceContext(c config.Config) *ServiceContext {

	//创建Redis实例
	newRedis := redis.New(c.Redis.Address, redisConfig(c))

	// 创建OSSClient实例
	newOss, err := oss.New(c.Oss.Endpoint, c.Oss.AccessKeyID, c.Oss.SecretAccessKey, oss.Timeout(10, 120))
	if err != nil {
		log.Fatalln(err)
	}

	_ = newRedis.Setex("测试Redis!", "Redis测试成功", 1)
	a, _ := newRedis.Get("测试Redis!")
	tool.GLogLine("设置Redis过期时间为1秒")
	tool.GLogLine("1秒前的Redis为：", a)
	time.Sleep(1 * time.Second)
	b, _ := newRedis.Get("测试Redis!")
	tool.GLogLine("1秒后的Redis为：", b)

	return &ServiceContext{
		Config:    c,
		CheckUrl:  middleware.NewCheckUrlMiddleware(newRedis).Handle,
		Redis:     newRedis,
		OssClient: newOss,
		Sys:       sys.NewSys(zrpc.MustNewClient(c.SysRpc)),
		Card:      card.NewCard(zrpc.MustNewClient(c.CardRpc)),
	}
}

func redisConfig(c config.Config) redis.Option {
	return func(r *redis.Redis) {
		r.Type = redis.NodeType
		r.Pass = c.Redis.Pass
		r.Addr = c.Redis.Address
	}
}
